package mws;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class MapperHolder {
    // 同步消息缓存
    private static final Map<String, Integer> ReduceCount = new ConcurrentHashMap<>();

    private static final ReentrantReadWriteLock sharingLock = new ReentrantReadWriteLock();
    private static final ReentrantReadWriteLock.ReadLock readLock = sharingLock.readLock();
    private static final ReentrantReadWriteLock.WriteLock writeLock = sharingLock.writeLock();

    public static boolean putMapper(String key, Integer value) {
            if (ReduceCount.putIfAbsent(key, value) == null) {
                return true;
            }
        try {
            writeLock.lock();
            ReduceCount.compute(key, (k, oldValue) ->{
                if (oldValue != null) {// 其实这里不会空指针 因为没有删除 666
                    return oldValue + value;
                }
                return value;
            });
            return false;
        } finally {
            writeLock.unlock();
        }
    }

    public static Integer getMapper(String key) {
        try {
            readLock.lock();
            return ReduceCount.get(key);
        } finally {
            readLock.unlock();
        }


    }

    public static void removeMapper(String key,Integer value) {
        try {
            writeLock.lock();
            Integer integer = ReduceCount.get(key);
            if(integer != null) {
                integer = integer - value;
                if(integer <= 0) {
                    ReduceCount.remove(key);
                } else {
                    ReduceCount.put(key, integer);
                }
            }else {
                ReduceCount.remove(key);
            }
        } finally {
            writeLock.unlock();
        }
    }

}
